package com.dudy.authdemo.service.impl;

import com.dudy.authdemo.model.Person;
import com.dudy.authdemo.service.MenuService;
import com.dudy.authdemo.service.PersonService;
import com.dudy.authdemo.vo.MenuVO;
import com.dudy.authdemo.vo.PersonVO;
import com.dudy.common.base.ResultCode;
import com.dudy.common.util.DingTalkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: auth
 * @author: dudy
 * @create: 2020-12-15 17:34
 * @description:
 **/
@Service
public class JwtUserDetailServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(JwtUserDetailServiceImpl.class);

    @Autowired
    private PersonService personService;

    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        Assert.notEmpty(username, "登陆账号不能为空");
        Example example = new Example(Person.class);
        example.createCriteria().andEqualTo("deleteFlag", 0).andEqualTo("username", username);
        List<PersonVO> personVOS = null;
        try {
            personVOS = personService.selectByExample(example);
        } catch (Exception e) {
            throw new BadCredentialsException(ResultCode.LOGIN_INFO_NOT_EXIST.getMassage());
        }
        if (CollectionUtils.isEmpty(personVOS)) {
            throw new BadCredentialsException(ResultCode.LOGIN_INFO_NOT_EXIST.getMassage());
        }
        if (personVOS.size() > 1) {
            log.error("账号重复，账号为：{}", username);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "loadUserByUsername", username, null);
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(username, personVOS.get(0).getPassword(), new ArrayList<>());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        return new User(username,
                personVOS.get(0).getPassword() + "_" + personVOS.get(0).getSalt(), new ArrayList<>());
    }
}
